//
//  FourTCViewController.swift
//  swiftTS
//
//  Created by 航电 on 2020/3/5.
//  Copyright © 2020 航电. All rights reserved.
//

import UIKit

class FourTCViewController: UIViewController {

    fileprivate var isScrollDown = true;
    fileprivate var lastOffsetY:CGFloat = 0;
    fileprivate let leftTableWidth = 120;
    fileprivate lazy var leftTableView:UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: leftTableWidth, height: Int(screenMainSize.height)), style: UITableView.Style.plain);
        tableView.backgroundColor = .white;
        tableView.showsVerticalScrollIndicator = false;
        tableView.showsHorizontalScrollIndicator = false;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.separatorStyle = .none;
        return tableView;
    }();
    
    fileprivate lazy var flowLayout:UICollectionViewFlowLayout = {
        let flowLayout = UICollectionViewFlowLayout();
        flowLayout.scrollDirection = .vertical;
        return flowLayout;
    }();
    
    fileprivate lazy var rightCollectionView:UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect(x: self.leftTableView.frame.maxX, y: 0, width: screenMainSize.width-self.leftTableView.frame.maxX, height: screenMainSize.height), collectionViewLayout: self.flowLayout);
        collectionView.showsHorizontalScrollIndicator = false;
        collectionView.showsVerticalScrollIndicator = false;
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = .white;
        collectionView.register(FourCollectionCell.self, forCellWithReuseIdentifier: "four_tc_collectionCell");
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "four_tc_collection_headerview");
        return collectionView;
    }();
    
    fileprivate lazy var dataArray:NSMutableArray = {
        var dataArr = NSMutableArray();
        
        let filePath = Bundle.main.path(forResource: "Four", ofType: "plist");
        let fileArr = NSArray(contentsOfFile: filePath ?? "");
        dataArr.addObjects(from: fileArr as! [Any]);
        
        return dataArr;
    }();
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "tableView和collectionView联动";
        // Do any additional setup after loading the view.
        self.onCreateUIForView();
    }

    //TODO:UI
    func onCreateUIForView() {
        self.view.backgroundColor = .white;
        
        self.view.addSubview(self.leftTableView);
        self.view.addSubview(self.rightCollectionView);
    }

    //TODO:Actions
    fileprivate func onSelectTableView(index:Int) {
        self.leftTableView.selectRow(at: NSIndexPath(row: index, section: 0) as IndexPath, animated: true, scrollPosition: .middle);
    }
}

extension FourTCViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count;
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellId = "four_tc_cell";
        var cell = tableView.dequeueReusableCell(withIdentifier: cellId);
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: cellId);
            cell?.backgroundColor = .lightGray;
        }
        
        if self.dataArray.count > indexPath.row {
            let dic:Dictionary<String,AnyObject> = self.dataArray.object(at: indexPath.row) as! Dictionary;
            cell?.textLabel?.text = dic["name"] as? String;
        }
        
        return cell!;
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.rightCollectionView.selectItem(at: NSIndexPath(row: 0, section: indexPath.row) as IndexPath, animated: true, scrollPosition: .top);
    }
}

extension FourTCViewController:UICollectionViewDelegate,UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.dataArray.count;
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.dataArray.count > section {
            let dic:Dictionary<String,AnyObject> = self.dataArray.object(at: section) as! Dictionary;
            let datArray:Array<String> = dic["data"] as! Array;
            return datArray.count;
        }
        return 0;
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellId = "four_tc_collectionCell";
        let cell:FourCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FourCollectionCell;
        
        if self.dataArray.count > indexPath.section {
            let dic:Dictionary<String,AnyObject> = self.dataArray.object(at: indexPath.section) as! Dictionary;
            let datArray:Array<String> = dic["data"] as! Array;
            if datArray.count > indexPath.row {
                let titleName = datArray[indexPath.row];
                let picName = (indexPath.row % 2) == 0 ? "bg_calendar_date" : "watch_scanner_fragment_icon";
                let dic = ["img":picName,"title":titleName];
                cell.onChangeData(dic: dic as Dictionary<String, AnyObject>);
            }
        }
        
        return cell;
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        //组头和组尾 该方法响应需要注册以及高度方法响应

        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "four_tc_collection_headerview", for: indexPath);
        headerView.backgroundColor = .purple;
        
        var titleLb = headerView.viewWithTag(1200) as? UILabel;
        if titleLb == nil {
            titleLb = UILabel(frame: headerView.bounds) ;
            titleLb!.textAlignment = .center;
            titleLb!.textColor = .white;
            titleLb!.tag = 1200;
            headerView.addSubview(titleLb!);
            
        }
        if self.dataArray.count > indexPath.section {
            let dic:Dictionary<String,AnyObject> = self.dataArray.object(at: indexPath.section) as! Dictionary;
            titleLb!.text = (dic["name"] as! String);
        }
        
        return headerView;
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if (self.rightCollectionView == scrollView) {
            isScrollDown = lastOffsetY < scrollView.contentOffset.y;
            lastOffsetY = scrollView.contentOffset.y;
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
        if elementKind == UICollectionView.elementKindSectionHeader {
            if !self.isScrollDown && collectionView.isDragging {
                //将要显示组头 方向是向上
                self.onSelectTableView(index: indexPath.section);
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
        if self.isScrollDown && collectionView.isDragging {
            //将要显示组头 方向是向上
            self.onSelectTableView(index: indexPath.section+1);
        }
    }
    
}

extension FourTCViewController:UICollectionViewDelegateFlowLayout {
    //每个item的size
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let collectionViewWidth = screenMainSize.width-self.leftTableView.frame.maxX;
        let itemSize = CGSize(width: (collectionViewWidth-2*2-10*3-8*3)/3, height: (collectionViewWidth-5*2)/3);
        return itemSize;
    }
    
    //每个item的内间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 5, left: 10, bottom: 0, right: 8);
    }

    //每行间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10;
    }

    //每个item的间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 2;
    }

    //组头的size
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 40);
    }

    //组尾的size
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 0);
    }
}
